package com.luqili.utils.pub.jobs;

/**
 * 工作线程，增加停止功能扩展
 *
 * @author luqili
 */
public class JobThread extends Thread {
    protected boolean jobRun = true;
    private Runnable target;

    public JobThread() {
        super();
    }

    public JobThread(Runnable target) {
        super();
        this.target = target;
    }

    public JobThread(String name) {
        super(name);
    }

    public void setRunnable(Runnable target) {
        this.target = target;
    }

    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

    /**
     * 结束工作，需要运行方法支持jobRun属性
     */
    public void endJob() {
        jobRun = false;
    }

    /**
     * 获取设定的状态
     *
     * @return
     */
    public boolean getJobRun() {
        return jobRun;
    }

    /**
     * 超时时间
     *
     * @param timeOut
     */
    @SuppressWarnings("deprecation")
    public void forceEndJob(long timeOut) {
        endJob();
        long count = timeOut / 300;// 检查次数
        for (int i = 0; i <= count; i++) {
            if (this.isAlive()) {
                endJob();
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                }
            } else {
                // 线程已结束
                return;
            }
        }
        if (this.isAlive()) {
            try {
                this.stop();
            } catch (Exception e) {

            }
        }
    }
}
